package com.zhuoyue.system.service.impl;

import com.zhuoyue.system.mapper.AgentStoreMapper;
import com.zhuoyue.system.service.FileUploadService;
import com.zhuoyue.system.service.ISysImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhanghui
 * @date 2021/11/5 16:26
 */
@Service
public class SysImageServiceImpl implements ISysImageService {
    private final String customDomain = "https://www.img.zyzncloud.com/";
    private final String storeFilePrefix = "zyzn/agent/";

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    AgentStoreMapper agentStoreMapper;

    @Override
    public void removeStoreImg() {
        List<String> imgList = agentStoreMapper.getImgList();
        List<String> shouldRemoveFileUidList = getShouldRemoveFileUidList(fileUploadService.getFileUidList(storeFilePrefix), imgList);
        System.out.println("=======shouldRemoveFileUidList=======");
        for (String s : shouldRemoveFileUidList) {
            System.out.println(s);
        }

    }

    /**
     * 获取可以删除的文件的id（两者差集）
     *
     * @param ossUidList      云端存储的列表
     * @param databaseUidList 数据库中的文件列表
     * @return
     */
    private List<String> getShouldRemoveFileUidList(List<String> ossUidList, List<String> databaseUidList) {
        System.out.println("=======ossUidList======");
        for (String s : ossUidList) {
            System.out.println(s);
        }
        System.out.println("=====databaseUidList=====");
        splitCustomDomain(databaseUidList);
        for (String s : databaseUidList) {
            System.out.println(s);
        }

        ossUidList.removeAll(databaseUidList);
        return ossUidList;
    }

    private void splitCustomDomain(List<String> fileUidList) {
        for (int i = 0; i < fileUidList.size(); i++) {
            String sourceUrl = fileUidList.get(i);
            if (sourceUrl.startsWith(customDomain)) {
                fileUidList.set(i, sourceUrl.substring(customDomain.length()));
            }
        }
    }
}
